home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 589 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: news.umbc.edu!not-for-mail
  2. From: schlein@umbc.edu (Jonas J. Schlein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: RANDOM NUMBER GENERATOR
  5. Date: 7 Jan 1996 11:42:14 -0500
  6. Organization: University of Maryland Baltimore County
  7. Message-ID: <4cot56$f3d@umbc9.umbc.edu>
  8. References: <4cniff$11o$1@mhade.production.compuserve.com>
  9. NNTP-Posting-Host: f-umbc9.umbc.edu
  10. NNTP-Posting-User: schlein
  11.  
  12. Merlin Chowkwanyun  <71702.1123@CompuServe.COM> wrote:
  13. |> Just thought you might like to know that I found this random number
  14. |> generator lying around in an old C++ magazine
  15. |> 
  16. |> /declares a global random number generating function
  17. |> 
  18. |> int random(int MaxVal)
  19. |> {
  20. |>  return rand() % MaxVal;
  21. |> }
  22. |> 
  23. |> Be sure to include the header file stdlib.h
  24.  
  25. That will certainly return a random number in the range [0,MaxVal), but isn't
  26. the best way to do it. Here's why:
  27.  
  28. 13.16:    How can I get random integers in a certain range?
  29.  
  30. A:    The obvious way,
  31.  
  32.         rand() % N        /* POOR */
  33.  
  34.     (which tries to return numbers from 0 to N-1) is poor, because
  35.     the low-order bits of many random number generators are
  36.     distressingly *non*-random.  (See question 13.18.)  A better
  37.     method is something like
  38.  
  39.         (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  40.  
  41.     If you're worried about using floating point, you could use
  42.  
  43.         rand() / (RAND_MAX / N + 1)
  44.  
  45.     Both methods obviously require knowing RAND_MAX (which ANSI
  46.     #defines in <stdlib.h>), and assume that N is much less than
  47.     RAND_MAX.
  48.  
  49.     (Note, by the way, that RAND_MAX is a *constant* telling you
  50.     what the fixed range of the C library rand() function is.  You
  51.     cannot set RAND_MAX to some other value, and there is no way of
  52.     requesting that rand() return numbers in some other range.)
  53.  
  54.     If you're starting with a random number generator which returns
  55.     floating-point values between 0 and 1, all you have to do to get
  56.     integers from 0 to N-1 is multiply the output of that generator
  57.     by N.
  58.  
  59.     References: K&R2 Sec. 7.8.7 p. 168; PCS Sec. 11 p. 172.
  60. -- 
  61. "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
  62.  
  63. Jonas J. Schlein  (schlein@gl.umbc.edu)
  64.